<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/3/16
 * Time: 13:16
 */

namespace app\admin\controller;


use app\admin\model\Reward as AdminModel;
use think\Config;
use think\Loader;

class Reward extends Admin
{
    protected $code_name = '奖励';

    public function set_param(){
        parent::set_param();
        $this->assign('code','reward');
        $this->assign('code_name',$this->code_name);
        $this->admin_model = new AdminModel();
    }

    public function index()
    {
        $active_id = $this->request->param('active_id');

        if(empty($active_id)){
            $this->error('活动id丢失');
        }
        $list = $this->admin_model->where('active_id',$active_id)->order('sort desc')->paginate(10);
        return view('',['list'=>$list,'page'=>$list->render(),'active_id'=>$active_id]);
    }

    public function after_read_model()
    {
        $this->assign('active_id',$this->request->param('active_id'));
    }

    public function create($post)
    {
        $res = $this->change($post);
        if($res){
            return json(['code'=>999,'message'=>$res]);
        }
        $this->admin_model->current_number = $post['number'];
        $this->admin_model->save();
        return $this->return_json(0,'新增'.$this->code_name.'成功,即将跳转'.$this->code_name.'列表');
    }

    public function update($post)
    {
        $res = $this->change($post);
        if($res){
            return json(['code'=>999,'message'=>$res]);
        }
        if(!empty($post['edit_number']) && $post['edit_number'] == 1){
            $this->admin_model->current_number = $post['current_number'];
        }
        $this->admin_model->save();
        return $this->return_json(0,'编辑'.$this->code_name.'成功,即将跳转'.$this->code_name.'列表');
    }

    private function change($post)
    {
        $validate = Loader::validate('Reward');
        if(!$validate->check($post)){
            return $validate->getError();
        }
        if($post['reward_cate'] == 1 && empty($post['receive_address'])){
            return '兑奖地址不能为空';
        }
        $this->admin_model->active_id = $post['active_id'];
        $this->admin_model->name = htmlspecialchars($post['name']);
        $this->admin_model->number = $post['number'];
        $this->admin_model->sort = $post['sort'];
        $this->admin_model->status = $post['status'];
        $this->admin_model->is_endless = $post['is_endless'];
        $this->admin_model->is_log = $post['is_log'];
        $this->admin_model->tip_text = htmlspecialchars($post['tip_text']);
        $this->admin_model->reward_cate = $post['reward_cate'];
        $this->admin_model->receive_address = htmlspecialchars($post['receive_address']);
        return false;
    }
}